package com.windystory.wslibrary.base.photoShow;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.windystory.wslibrary.R;
import com.windystory.wslibrary.base.activity.BaseActivity;
import com.windystory.wslibrary.util.DownloadUtil;
import com.windystory.wslibrary.util.LogUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * ShowPicActivity
 * Created by windystory on 08/23/2019.
 */
public class ShowPicActivity extends BaseActivity {

    private ImageView close;
    private ImageView share;
    private ImageView download;
    private TextView tips;

    private ViewPager vp;
    private List<Fragment> fragmentLists = new ArrayList<>();
    private List<String> picturesList = new ArrayList<>();
    private int currentPosition = 0;

    public static final int SUCCESS = 200;//成功
    public static final int FAILED = 500;//失败
    public static final int PROGRESS = 100;//进行中

    @Override
    public int getLayoutRes() {
        return R.layout.activity_show_pics;
    }

    @Override
    protected boolean setEnableSwipeBack() {
        return true;
    }

    /**
     * 跳转
     *
     * @param activity
     * @param picsList
     * @param position
     */
    public static void startActivity(Activity activity, List<String> picsList, int position) {
        Intent i = new Intent(activity, ShowPicActivity.class);
        i.putExtra("picsList", (Serializable) picsList);
        i.putExtra("position", position);
        activity.startActivity(i);
    }


    @Override
    protected void initView() {
        vp = (ViewPager) findViewById(R.id.vp);
        close = (ImageView) findViewById(R.id.close);
        share = (ImageView) findViewById(R.id.share);
        download = (ImageView) findViewById(R.id.download);
        tips = (TextView) findViewById(R.id.tips);
    }

    @Override
    protected void initData() {
        getSupportActionBar().hide();
        fragmentLists.addAll(initGuideFragments());
        ViewPageAdapter adapter = new ViewPageAdapter(getSupportFragmentManager(), fragmentLists);
        vp.setAdapter(adapter);


        //设置当前图片position
        if (currentPosition <= picturesList.size()) {
            vp.setCurrentItem(currentPosition);
        } else {
            vp.setCurrentItem(0);
        }
        //设置位置
        tips.setText((currentPosition + 1) + "/" + picturesList.size());

        ImmersionBar.with(this)
                .statusBarColor(R.color.black)
                .init();
    }


    @Override
    protected void initListener() {
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                tips.setText((i + 1) + "/" + picturesList.size());
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        download.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View v) {
                savePic(picturesList.get(vp.getCurrentItem()));
            }
        });
    }

    /**
     * 保存图片
     *
     * @param imgs
     */
    private void savePic(final String imgs) {
        new RxPermissions(ShowPicActivity.this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean result) {
                        if (result) {
                            //创建目录
                            DownloadUtil.get().download(ShowPicActivity.this, imgs,
                                    Environment.getDataDirectory().getAbsolutePath(),
                                    System.currentTimeMillis() + ".jpg",
                                    new DownloadUtil.OnDownloadListener() {
                                        @Override
                                        public void onDownloadSuccess() {
                                            LogUtil.e("保存成功！");
                                            handler.sendEmptyMessage(SUCCESS);
                                        }

                                        @Override
                                        public void onDownloading(int progress) {
                                            LogUtil.e("保存中");
                                            handler.sendEmptyMessage(PROGRESS);
                                        }

                                        @Override
                                        public void onDownloadFailed() {
                                            LogUtil.e("保存失败,请重新尝试");
                                            handler.sendEmptyMessage(FAILED);
                                        }
                                    });
                        } else {
                            Toast.makeText(ShowPicActivity.this, "请您允许相关权限，否则无法进行存储", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 刷新UI
     */
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    download.setClickable(true);
                    Toast.makeText(ShowPicActivity.this, "保存成功，图片已保存到 /Download/data/ 下", Toast.LENGTH_SHORT).show();
                    break;
                case FAILED:
                    download.setClickable(true);
                    Toast.makeText(ShowPicActivity.this, "保存失败，请重新尝试", Toast.LENGTH_SHORT).show();
                    break;
                case PROGRESS://进行中
                    download.setClickable(false);
                    break;

            }
            return false;
        }
    });

    /**
     * ViewPageAdapter适配器
     */
    public class ViewPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;

        ViewPageAdapter(FragmentManager fm, List<Fragment> fragmentList) {
            super(fm);
            this.fragmentList = fragmentList;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

    }


    /**
     * 初始化Fragment
     * <p>
     * List<Fragment> fragments = new ArrayList<>();
     * fragments.add(new BaseGuideFragment().newInstance(R.drawable.b1));
     * fragments.add(new BaseGuideFragment().newInstance(R.drawable.b2));
     * fragments.add(new BaseGuideFragment().newInstance(R.drawable.b3));
     * fragments.add(new LastGuideFragment());
     * return fragments;
     */
    private List<Fragment> initGuideFragments() {
        List<Fragment> fragmentLists = new ArrayList<>();
        //转化图片
        picturesList.clear();
        picturesList.addAll(getIntent().getStringArrayListExtra("picsList"));
        currentPosition = getIntent().getIntExtra("position", 0);

        LogUtil.e(currentPosition + "---->position" + "  " + picturesList.size());

        if (picturesList != null && picturesList.size() > 0) {
            for (int i = 0; i < picturesList.size(); i++) {
                fragmentLists.add(ShowPicsFragment.newInstance(picturesList.get(i)));
            }
        } else {
            fragmentLists.add(ShowPicsErrorFragment.newInstance(""));
        }

        return fragmentLists;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }
}
